/**
 * 路由相关工具函数
 */

import type { RouteRecordRaw } from 'vue-router'
import type { BaseRoute } from '@/types/router'

// 使用 import.meta.glob 预先收集所有视图组件
const viewModules = import.meta.glob('@/views/**/index.vue')

/**
 * 根据组件路径获取对应的组件加载函数
 * @param componentPath 组件路径，如 '/dashboard/home'
 * @returns 组件加载函数
 */
const getComponentLoader = (componentPath: string) => {
    const fullPath = `/src/views${componentPath}/index.vue`

    if (viewModules[fullPath]) {
        return viewModules[fullPath]
    }

    // 如果找不到对应组件，返回占位符组件
    console.warn(`Component not found: ${fullPath}, using placeholder`)
    return viewModules['@/views/placeholder/index.vue'] || (() => import('@/views/placeholder/index.vue'))
}

/**
 * 将BaseRoute转换为Vue Router格式
 * @param routes BaseRoute数组
 * @returns Vue Router格式的路由数组
 */
export const convertToVueRoutes = (routes: BaseRoute[]): RouteRecordRaw[] => {
    const transform = (route: BaseRoute): RouteRecordRaw => {
        const result: Partial<RouteRecordRaw> = {
            path: route.path,
            name: route.name,
            meta: route.meta,
        }

        if (route.component) {
            result.component =
                typeof route.component === 'string'
                    ? getComponentLoader(route.component)
                    : route.component || getComponentLoader('/placeholder')
        }

        if (route.children && route.children.length > 0) {
            result.children = route.children.map((child) => transform(child))
        }

        return result as unknown as RouteRecordRaw
    }

    return routes.map((r) => transform(r))
}

/**
 * 加载路由模块的通用方法
 * @param routeFiles - 通过 import.meta.glob 获取的路由文件模块
 * @returns 路由记录数组
 */
export const loadRouteModules = (routeFiles: Record<string, unknown>): RouteRecordRaw[] => {
    const routes: RouteRecordRaw[] = []

    for (const [filePath, routeModule] of Object.entries(routeFiles)) {
        const module = (routeModule as { default?: RouteRecordRaw[] }).default

        if (!module) {
            console.warn(`路由模块 ${filePath} 没有导出 default`)
            continue
        }

        if (!Array.isArray(module)) {
            console.warn(`路由模块 ${filePath} 的 default 导出不是数组格式`)
            continue
        }

        routes.push(...module)
    }

    return routes
}

/**
 * 检查路由是否需要权限验证
 * @param routeName 路由名称
 * @param coreRouteNames 核心路由名称数组
 * @returns 是否需要权限验证
 */
export const needsPermissionCheck = (routeName: string, coreRouteNames: string[]): boolean => {
    return !coreRouteNames.includes(routeName)
}
